// pages/role-management/index.js
const { auth } = require('../../utils/auth')
const Toast = require('@vant/weapp/toast/toast')
const Dialog = require('@vant/weapp/dialog/dialog')

Page({
  data: {
    loading: true,
    adminList: [],
    partnerList: [],
    stats: {
      adminCount: 0,
      partnerCount: 0,
      totalUsers: 0
    },
    
    // 重置密码相关
    showResetDialog: false,
    currentUser: null,
    newPassword: '',
    confirmPassword: ''
  },

  onLoad() {
    // 检查管理员权限
    if (!auth.isAdmin()) {
      Toast.fail('无权限访问此页面')
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    this.loadRoleData()
  },

  onShow() {
    // 页面显示时刷新数据
    if (auth.isAdmin()) {
      this.loadRoleData()
    }
  },

  // 加载角色数据
  async loadRoleData() {
    this.setData({ loading: true })
    
    try {
      const [adminResponse, partnerResponse] = await Promise.all([
        this.getAdminList(),
        this.getPartnerList()
      ])
      
      const adminList = adminResponse.success ? adminResponse.data : []
      const partnerList = partnerResponse.success ? partnerResponse.data : []
      
      this.setData({
        adminList,
        partnerList,
        stats: {
          adminCount: adminList.length,
          partnerCount: partnerList.length,
          totalUsers: adminList.length + partnerList.length
        }
      })
    } catch (error) {
      console.error('加载角色数据失败:', error)
      Toast.fail('加载数据失败')
    } finally {
      this.setData({ loading: false })
    }
  },

  // 获取管理员列表
  getAdminList() {
    return new Promise((resolve, reject) => {
      const app = getApp()
      const baseUrl = app.globalData.baseUrl || 'http://localhost:8080'
      
      wx.request({
        url: `${baseUrl}/api/user-role/admins`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${auth.getToken()}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.data?.message || '获取管理员列表失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 获取伴侣列表
  getPartnerList() {
    return new Promise((resolve, reject) => {
      const app = getApp()
      const baseUrl = app.globalData.baseUrl || 'http://localhost:8080'
      
      wx.request({
        url: `${baseUrl}/api/user-role/partners`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${auth.getToken()}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.data?.message || '获取伴侣列表失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 重置密码
  onResetPassword(e) {
    const user = e.currentTarget.dataset.user
    this.setData({
      showResetDialog: true,
      currentUser: user,
      newPassword: '',
      confirmPassword: ''
    })
  },

  // 密码输入
  onPasswordChange(e) {
    this.setData({
      newPassword: e.detail
    })
  },

  // 确认密码输入
  onConfirmPasswordChange(e) {
    this.setData({
      confirmPassword: e.detail
    })
  },

  // 确认重置密码
  async onConfirmReset() {
    const { newPassword, confirmPassword, currentUser } = this.data
    
    if (!newPassword) {
      Toast.fail('请输入新密码')
      return
    }
    
    if (newPassword.length < 6) {
      Toast.fail('密码至少6位')
      return
    }
    
    if (newPassword !== confirmPassword) {
      Toast.fail('两次密码不一致')
      return
    }
    
    try {
      const response = await this.resetAdminPassword(currentUser.userId, newPassword)
      
      if (response.success) {
        Toast.success('密码重置成功')
        this.setData({
          showResetDialog: false,
          currentUser: null,
          newPassword: '',
          confirmPassword: ''
        })
      } else {
        Toast.fail(response.message || '密码重置失败')
      }
    } catch (error) {
      console.error('重置密码失败:', error)
      Toast.fail('密码重置失败')
    }
  },

  // 取消重置密码
  onCancelReset() {
    this.setData({
      showResetDialog: false,
      currentUser: null,
      newPassword: '',
      confirmPassword: ''
    })
  },

  // 重置管理员密码API
  resetAdminPassword(userId, newPassword) {
    return new Promise((resolve, reject) => {
      const app = getApp()
      const baseUrl = app.globalData.baseUrl || 'http://localhost:8080'
      
      wx.request({
        url: `${baseUrl}/api/user-role/reset-password`,
        method: 'POST',
        data: {
          userId,
          newPassword
        },
        header: {
          'Authorization': `Bearer ${auth.getToken()}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.data?.message || '重置密码失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 切换用户状态
  async onToggleStatus(e) {
    const user = e.currentTarget.dataset.user
    const newStatus = !user.isActive
    
    try {
      const response = await this.updateRoleStatus(user.userId, newStatus)
      
      if (response.success) {
        Toast.success(newStatus ? '启用成功' : '禁用成功')
        this.loadRoleData() // 刷新数据
      } else {
        Toast.fail(response.message || '操作失败')
      }
    } catch (error) {
      console.error('切换状态失败:', error)
      Toast.fail('操作失败')
    }
  },

  // 更新角色状态API
  updateRoleStatus(userId, isActive) {
    return new Promise((resolve, reject) => {
      const app = getApp()
      const baseUrl = app.globalData.baseUrl || 'http://localhost:8080'
      
      wx.request({
        url: `${baseUrl}/api/user-role/status`,
        method: 'PUT',
        data: {
          userId,
          isActive
        },
        header: {
          'Authorization': `Bearer ${auth.getToken()}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.data?.message || '更新状态失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 删除角色
  onDeleteRole(e) {
    const user = e.currentTarget.dataset.user
    
    Dialog.confirm({
      title: '确认删除',
      message: `确定要删除用户 "${user.nickname}" 的角色吗？此操作不可恢复。`,
    }).then(async () => {
      try {
        const response = await this.deleteUserRole(user.userId)
        
        if (response.success) {
          Toast.success('删除成功')
          this.loadRoleData() // 刷新数据
        } else {
          Toast.fail(response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除角色失败:', error)
        Toast.fail('删除失败')
      }
    }).catch(() => {
      // 用户取消删除
    })
  },

  // 删除用户角色API
  deleteUserRole(userId) {
    return new Promise((resolve, reject) => {
      const app = getApp()
      const baseUrl = app.globalData.baseUrl || 'http://localhost:8080'
      
      wx.request({
        url: `${baseUrl}/api/user-role/${userId}`,
        method: 'DELETE',
        header: {
          'Authorization': `Bearer ${auth.getToken()}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.data?.message || '删除失败'))
          }
        },
        fail: reject
      })
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadRoleData().finally(() => {
      wx.stopPullDownRefresh()
    })
  }
})